#include "pageusermgmt.h"
#include "ui_pageusermgmt.h"
#include <QMainWindow>
#include <QMessageBox>
#include <QSqlError>
#include <QDebug>
#include <QSqlQuery>
#include <QStandardItemModel>
#include <QStyledItemDelegate>
#include <QPainter>
#include <QtGui>
#include <QDateTime>

// 定义静态变量
QString pageUserMgmt::originalOldUsername = "";
QString pageUserMgmt::Tempusername = "";
QString pageUserMgmt::deletedUsers = "";
QString pageUserMgmt::loginUsername = "";

pageUserMgmt::pageUserMgmt(Mainbar *mainbar,QWidget *parent) :
    QWidget(parent),
    ui(new Ui::pageUserMgmt),
    m_mainbar(mainbar)
{
    ui->setupUi(this);

    m_logManager = new LogManager(this);
    // 初始化模型
    QSqlDatabase db = DatabasePool::instance().getConnection();
    m_model = new QSqlTableModel(this, db);
    m_model->setTable("users");
    m_model->setEditStrategy(QSqlTableModel::OnManualSubmit);

    if (!m_model->select()) {
        qDebug() << "Failed to select data:" << m_model->lastError().text();
    }

    // 设置表头中文显示
    m_model->setHeaderData(1, Qt::Horizontal, "用户名");
    m_model->setHeaderData(3, Qt::Horizontal, "邮箱");
    m_model->setHeaderData(4, Qt::Horizontal, "手机号");
    m_model->setHeaderData(5, Qt::Horizontal, "用户类型");
    m_model->setHeaderData(6, Qt::Horizontal, "注册日期");
    m_model->setHeaderData(7, Qt::Horizontal, "修改日期");

    // 配置代理模型
    m_proxyModel = new QSortFilterProxyModel(this);
    m_proxyModel->setSourceModel(m_model);
    m_proxyModel->setFilterKeyColumn(1);

    // 配置表格视图
    ui->tableView->setModel(m_proxyModel);
    ui->tableView->setColumnHidden(0, true);
    ui->tableView->setColumnHidden(2, true);
    ui->tableView->setItemDelegateForColumn(6, new DateTimeDelegate(this));
    ui->tableView->setItemDelegateForColumn(7, new DateTimeDelegate(this));

    // 创建居中委托实例
    CenteredItemDelegate *centeredDelegate = new CenteredItemDelegate(this);
    for (int col = 0; col < m_model->columnCount(); ++col) {
        ui->tableView->setItemDelegateForColumn(col, centeredDelegate);
    }

    // 用户名列（第1列）设置只读委托
    ui->tableView->setItemDelegateForColumn(1, new ReadOnlyDelegate(this));
    ui->tableView->setItemDelegateForColumn(6, new ReadOnlyDelegate(this));
    ui->tableView->setItemDelegateForColumn(7, new ReadOnlyDelegate(this));

    // 自适应列宽
    ui->tableView->resizeColumnsToContents();
    // 手动加宽特定列（单位：像素）
    ui->tableView->setColumnWidth(1, 120);
    ui->tableView->setColumnWidth(3, 180);
    ui->tableView->setColumnWidth(4, 180);
    ui->tableView->setColumnWidth(6, 180);
    ui->tableView->setColumnWidth(7, 180);

    // 在构造函数中启用多选模式
    ui->tableView->setSelectionMode(QAbstractItemView::ExtendedSelection);
    ui->tableView->setSelectionBehavior(QAbstractItemView::SelectRows);

    // 连接信号槽
    connect(ui->lineEditSearch, &QLineEdit::textChanged, this, &pageUserMgmt::onSearch);
    connect(ui->btnDeleteuser, &QPushButton::clicked, this, &pageUserMgmt::onDeleteUser);
    connect(ui->btnSave, &QPushButton::clicked, this, &pageUserMgmt::onSaveChanges);
    connect(ui->btnUpdate, &QPushButton::clicked, this, &pageUserMgmt::refreshTable);
    connect(m_mainbar, &Mainbar::sendUsername, this, &pageUserMgmt::receiveUsername);

    DatabasePool::instance().releaseConnection(db);
}

pageUserMgmt::~pageUserMgmt()
{
    delete ui;
}

void pageUserMgmt::receiveUsername(const QString &username)
{
    loginUsername = username;
    qDebug() << "pageUserMgmt收到用户名:" << loginUsername;
}

// 访问器函数实现
QString pageUserMgmt::getOriginalOldUsername() {
    return originalOldUsername;
}

QString pageUserMgmt::getTempusername() {
    return Tempusername;
}

// 搜索功能
void pageUserMgmt::onSearch(const QString &text)
{
    m_proxyModel->setFilterFixedString(text);
}

// 删除用户
void pageUserMgmt::onDeleteUser()
{
    QModelIndexList selected = ui->tableView->selectionModel()->selectedRows();
    if (selected.isEmpty()) {
        QMessageBox::warning(this, "警告", "请先选择要删除的用户！");
        return;
    }

    QSqlDatabase db = m_model->database();
    db.transaction();
    deletedUsers = ""; // 清空静态变量
    bool hasError = false;

    for (const QModelIndex &index : selected) {
        Tempusername = m_proxyModel->data(index.siblingAtColumn(1)).toString();
        if (!m_userMgr.deleteUserByUsername(Tempusername)) {
            db.rollback();
            QMessageBox::critical(this, "错误", "删除失败:" + m_userMgr.getLastError());
            userInfo = m_userMgr.queryUserByUsernamePhoneMail(originalOldUsername,"","");
            userInfoLogin = m_userMgr.queryUserByUsernamePhoneMail(loginUsername,"","");
            // 记录操作日志
            if (m_logManager) {
                m_logManager->recordSystemLog(
                            QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"),
                            "OPERATION",
                            "ERROR",
                            QString("管理员[%1]删除[%2]的信息失败!").arg(userInfoLogin["username"].toString()).arg(Tempusername),
                            userInfoLogin["user_id"].toInt(),
                        -1
                        );
            }
            hasError = true;
            break;
        }
        if (!deletedUsers.isEmpty()) {
            deletedUsers += ", ";
        }
        deletedUsers += Tempusername;
    }

    if (!hasError) {
        db.commit();
        refreshTable();
        QMessageBox::information(this, "成功", "用户已删除");
         userInfoLogin = m_userMgr.queryUserByUsernamePhoneMail(loginUsername,"","");
        // 记录操作日志
        if (m_logManager) {
            m_logManager->recordSystemLog(
                        QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"),
                        "OPERATION",
                        "INFO",
                        QString("管理员[%1]删除[%2]的信息成功!").arg(userInfoLogin["username"].toString()).arg(deletedUsers),
                        userInfoLogin["user_id"].toInt(),
                    -1
                    );
        }
    }
    deletedUsers = ""; // 清空静态变量
}

// 保存修改
void pageUserMgmt::onSaveChanges() {
    QSqlTableModel *model = static_cast<QSqlTableModel*>(m_proxyModel->sourceModel());
    QModelIndexList selected = ui->tableView->selectionModel()->selectedRows();
    if (selected.isEmpty()) {
        qDebug() << "No rows selected.";
        QMessageBox::warning(this, "警告", "请先选择要修改的用户！");
        return;
    }

    QSqlDatabase db = model->database();
    db.transaction();

    bool hasError = false;
    for (const QModelIndex &proxyIndex : selected) {
        QModelIndex sourceIndex = m_proxyModel->mapToSource(proxyIndex);
        int row = sourceIndex.row();

        // 保存原始的旧用户名
        originalOldUsername = model->data(model->index(row, 1), Qt::DisplayRole).toString();
        QString newUsername = model->data(model->index(row, 1), Qt::EditRole).toString();
        QString newEmail = model->data(model->index(row, 3), Qt::EditRole).toString();
        QString newPhone = model->data(model->index(row, 4), Qt::EditRole).toString();
        QString newRole = model->data(model->index(row, 5), Qt::EditRole).toString();


        // 数据验证
        if (newUsername.isEmpty() || newEmail.isEmpty() || newPhone.isEmpty() || newRole.isEmpty()) {
            QMessageBox::critical(this, "错误", "用户名、邮箱、手机和角色不能为空！");
            hasError = true;
            break;
        }

        // 打印调试信息
        qDebug() << "正在更新用户:" << originalOldUsername
                 << "=>" << newUsername
                 << "邮箱:" << newEmail
                 << "手机:" << newPhone;

        qDebug() << "传递给 updateByUsername 的 oldUsername: " << originalOldUsername;

        if (!m_userMgr.updateByUsername(originalOldUsername, newUsername, "", newEmail, newPhone, newRole)) {
            hasError = true;
            QMessageBox::critical(this, "错误", "保存失败：" + m_userMgr.getLastError());
            userInfoLogin = m_userMgr.queryUserByUsernamePhoneMail(loginUsername,"","");
            // 记录操作日志
            if (m_logManager) {
                m_logManager->recordSystemLog(
                            QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"),
                            "OPERATION",
                            "ERROR",
                            QString("管理员[%1]修改[%2]的信息失败!").arg(userInfoLogin["username"].toString()).arg(originalOldUsername),
                            userInfoLogin["user_id"].toInt(),
                        -1
                        );
            }
            break;
        }
    }

    if (hasError) {
        db.rollback();
        model->revertAll();
    } else {
        db.commit();
        refreshTable();
        QMessageBox::information(this, "成功", "修改已保存");
        userInfoLogin = m_userMgr.queryUserByUsernamePhoneMail(loginUsername,"","");
        // 记录操作日志
        if (m_logManager) {
            m_logManager->recordSystemLog(
                        QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"),
                        "OPERATION",
                        "INFO",
                        QString("管理员[%1]修改[%2]的信息成功!").arg(userInfoLogin["username"].toString()).arg(originalOldUsername),
                        userInfoLogin["user_id"].toInt(),
                    -1
                    );
        }
    }
}

// 刷新表格
void pageUserMgmt::refreshTable()
{
    m_model->select();
    m_proxyModel->invalidate();
}
